package cn.cms.util;

import cn.cms.annotation.Column;
import cn.cms.constants.ProductEnum;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by leon on 2017/3/21.
 */
public class Util {

    public static String getIpAddr(HttpServletRequest request) throws Exception {

        String ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

    public static String toDbColumn(Object object) {

        JSONObject jsonObject = new JSONObject();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {

            if (field.isAnnotationPresent(Column.class)) {

                String firstLetter = field.getName().substring(0, 1).toUpperCase();
                String column_name = field.getAnnotation(Column.class).name();
                String getter = "get" + firstLetter + field.getName().substring(1);
                try {
                    Method method = object.getClass().getMethod(getter, new Class[]{});
                    if (method.invoke(object, new Object[]{}) != null) {

                        Class<?> clazz = method.getReturnType();
                        String type = clazz.getName();
                        if (type.equals("java.util.Date")) {
                            Date date = (Date) method.invoke(object, new Object[]{});
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String dateString = formatter.format(date);
                            jsonObject.put(column_name, dateString);
                        } else {

                            if (StringUtils.isBlank(method.invoke(object, new Object[]{}).toString()) && column_name.equals("cover_image")) {

                                jsonObject.put(column_name, "[]");
                            } else {

                                jsonObject.put(column_name, method.invoke(object, new Object[]{}).toString());
                            }


                        }


                    }

                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        return jsonObject.toJSONString();
    }

    /**
     * @param pathName
     * @param content
     */
    public static void writeFile(String[] pathName, String[] content) {
        try {

            BufferedWriter bufferWriter = null;
            for (int i = 0; i < pathName.length; i++) {
                bufferWriter = new BufferedWriter(new FileWriter(pathName[i]));
                bufferWriter.write(content[i]);
                bufferWriter.flush();
            }

            bufferWriter.close();
        } catch (IOException e) {
            System.out.println("WriteFile-error==>>" + e.getMessage());
        }
    }

    public static String getProInfos(String pros) {
        StringBuilder sb = new StringBuilder();
        if (StringUtil.isNotEmptyOrNull(pros)) {
            String[] stpros = pros.split(",");
            for (String pro : stpros) {
                if ("141".equals(pro)) {
                    sb.append("1,");
                } else if ("171".equals(pro)) {
                    sb.append("2,");
                } else if ("210".equals(pro)) {
                    sb.append("303,");
                } else if ("212".equals(pro)) {
                    sb.append("304,");
                } else if ("214".equals(pro)) {
                    sb.append("305,");
                } else if ("216".equals(pro)) {
                    sb.append("306,");
                } else if ("161".equals(pro)) {
                    sb.append(ProductEnum.JRYS_OFF_LINE.getCms()).append(",");
                } else if ("181".equals(pro)) {
                    sb.append(ProductEnum.HJDQ_OFF_LINE.getCms()).append(",");
                } else if ("211".equals(pro)) {
                    sb.append(ProductEnum.ZIMAYS_OFF_LINE.getCms()).append(",");
                } else if ("213".equals(pro)) {
                    sb.append(ProductEnum.YSDQ_OFF_LINE.getCms()).append(",");
                }else if ("215".equals(pro)) {
                    sb.append(ProductEnum.YSDQ_POJIE_OFF_LINE.getCms()).append(",");
                }else if ("217".equals(pro)) {
                    sb.append(ProductEnum.MJDQ_OFF_LINE.getCms()).append(",");
                }
            }
            return sb.substring(0, sb.length() - 1);
        } else {
            return "";
        }
    }

    /**
     * 同步该板块下所有'合辑'类型条目生效产品线和所属板块(滤除该合辑在作品库未生效产品线)保持一致
     *
     * @param cmsEnabledPro
     * @param proEnabledPro
     * @return
     */
    public static String getSyncProFilterCmsPro(String cmsEnabledPro, String proEnabledPro) {
        if (StringUtil.isSpaceOrNull(cmsEnabledPro)) {
            return "";
        }
        if (StringUtil.isNotEmptyOrNull(proEnabledPro)) {
            String[] cmsEnabledPross = cmsEnabledPro.split(",");
            String[] proEnabledPross = proEnabledPro.split(",");
            List<String> cmsEnabledProList = new ArrayList<>(Arrays.asList(cmsEnabledPross));
            List<String> proEnabledProList = Arrays.asList(proEnabledPross);
            if (proEnabledProList.contains("161")) {
                cmsEnabledProList.remove("1");
                cmsEnabledProList.add("404");
            }
            if (proEnabledProList.contains("181")) {
                cmsEnabledProList.remove("2");
                cmsEnabledProList.add("405");
            }
            if (proEnabledProList.contains("211")) {
                cmsEnabledProList.remove("303");
                cmsEnabledProList.add("406");
            }
            if (proEnabledProList.contains("213")) {
                cmsEnabledProList.remove("304");
                cmsEnabledProList.add("407");
            }if (proEnabledProList.contains("215")) {
                cmsEnabledProList.remove("305");
                cmsEnabledProList.add("408");
            }
            if (proEnabledProList.contains("217")) {
                cmsEnabledProList.remove("306");
                cmsEnabledProList.add("409");
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cmsEnabledProList.size(); i++) {
                sb.append(cmsEnabledProList.get(i));
                if (i < cmsEnabledProList.size() - 1) {
                    sb.append(",");
                }
            }
            return sb.toString();
        }

        return cmsEnabledPro;
    }
}
